package com.sun.androidexerciseproject.function.permission.ui.permission;

import android.arch.lifecycle.ViewModelProviders;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.sun.androidexerciseproject.function.R;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

public class PermissionFragment extends Fragment {

    private PermissionViewModel mViewModel;
    private TextView mMessage;

    public static PermissionFragment newInstance() {
        return new PermissionFragment();
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container,
                             @Nullable Bundle savedInstanceState) {
        View root = inflater.inflate(R.layout.permission_fragment, container, false);
        initView(root);
        return root;
    }

    @Override
    public void onDestroy() {
        EventBus.getDefault().unregister(this);
        super.onDestroy();
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        mViewModel = ViewModelProviders.of(this).get(PermissionViewModel.class);
        mMessage.setText(String.valueOf(mViewModel.getNum()));
        // TODO: Use the ViewModel
    }

    private void initView(View root) {
        mMessage = root.findViewById(R.id.message);
        mMessage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mViewModel.setNum();
                EventBus.getDefault().post(new MessageEvent());
            }
        });
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(MessageEvent messageEvent) {
        mMessage.setText(String.valueOf(mViewModel.getNum()));
    }

    public static class MessageEvent {

    }

}
